#include <53func.h>
int main(int argc, char *argv[])
{
    // ./4_azhen_reconnect 192.168.38.128 1234
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET; // AF_INET ipv4
    addr.sin_port = htons(atoi(argv[2]));
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    int flag = 1; // 给SO_REUSEADDR属性的参数分配内存
    int ret = setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&flag,sizeof(flag));
    // 赋值用具体类型 传参时强转成公共类型
    ret = bind(sockfd,(struct sockaddr *)&addr, sizeof(addr));
    // 服务端 bind 只能绑定服务端地址
    ERROR_CHECK(ret,-1,"bind");
    listen(sockfd,10);
    char buf[4096] = {0};
    fd_set readyset; // 就绪集合
    fd_set monitorset; // 监听集合
    int netfd = -1; // -1 表示netfd不存在
    FD_ZERO(&monitorset);
    FD_SET(sockfd,&monitorset);
    while(1){ // 弄了一个备份的fdset
        memcpy(&readyset,&monitorset,sizeof(fd_set));// 用监听集合覆盖就绪
        select(100,&readyset,NULL,NULL,NULL); // select只会修改就绪集合
        if(FD_ISSET(sockfd,&readyset)){
            struct sockaddr_in client_addr;
            //// client_addr_length 应该要有一个合适的初始值
            socklen_t client_addr_length = sizeof(client_addr);
            netfd = accept(sockfd,
                               (struct sockaddr *)&client_addr,
                               &client_addr_length);
            printf("client ip = %s, port = %d\n",
                   inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

            FD_SET(netfd,&monitorset);
            FD_SET(STDIN_FILENO,&monitorset);
            FD_CLR(sockfd,&monitorset);
        }
        if(netfd != -1 && FD_ISSET(STDIN_FILENO,&readyset)){
            bzero(buf,sizeof(buf));
            ssize_t sret = read(STDIN_FILENO,buf,sizeof(buf));
            if(sret == 0){
                printf("nishigehaoren\n");
                close(netfd);
                FD_CLR(netfd,&monitorset);
                FD_CLR(STDIN_FILENO,&monitorset);
                FD_SET(sockfd,&monitorset);
                netfd = -1;
            }

            send(netfd,buf,strlen(buf),0);
        }
        if(netfd != -1 && FD_ISSET(netfd,&readyset)){
            bzero(buf,sizeof(buf));
            ssize_t sret = recv(netfd,buf,sizeof(buf),0);
            if(sret == 0){
                printf("wohuihaohaode\n");
                close(netfd);
                FD_CLR(netfd,&monitorset);
                FD_CLR(STDIN_FILENO,&monitorset);
                FD_SET(sockfd,&monitorset);
                netfd = -1;
            }
            printf("buf = %s\n", buf);
        }
    }
    return 0;
}

